﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using KL.Store.Data;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
using KL.Store.Web.Models;
using KL.Store.Core;
using KL.Store.Core.Domain;
using Cache = System.Web.Caching.Cache;

namespace KL.Store.Web.Controllers
{
    public class PartialsController : KL.Store.Core.Web.BaseController
    {
        #region Brands

        public ActionResult Brands(int full = 0, string id = "SelectedBrand")
        {
            ViewBag.ShowAll = full == 1 ? true : false;
            ViewBag.Id = id;

            var cacheManager = CacheFactory.GetCacheManager("Cache Manager");

            IList<ProductGroup> brands = (List<ProductGroup>)cacheManager.GetData("BrandsMenu");
            if (brands == null)
            {
                try
                {
                    brands = dbProduct.GetGroupList(Parameters.BrandCategoryId);
                    brands.Insert(0, new ProductGroup { GroupId = 0, GroupName = "Marka Seçiniz" });

                    cacheManager.Add("BrandsMenu", brands, CacheItemPriority.High, null, new AbsoluteTime(DateTime.Now.AddMinutes(5)));
                    cacheManager.Add("BrandsMenu_Long", brands, CacheItemPriority.High, null, new AbsoluteTime(DateTime.Now.AddDays(1)));
                }
                catch
                {
                    cacheManager.Add("BrandsMenu", cacheManager.GetData("BrandsMenu_Long").ToString(), CacheItemPriority.High, null, new AbsoluteTime(DateTime.Now.AddMinutes(5)));
                    brands = (List<ProductGroup>)cacheManager.GetData("BrandsMenu");
                }
            }

            BrandModel model = new BrandModel();
            model.Brands = brands;
            return PartialView(model);
        }

        #endregion

        #region Categories

        public ActionResult Categories(int MenuType = 0)
        {
            var cacheManager = CacheFactory.GetCacheManager("Cache Manager");

            string menustr = (string)cacheManager.GetData("CategoryMenu");
            if (menustr == null)
            {
                try
                {
                    menustr = dbCategory.GetMenu(Parameters.MainCategoryId);
                    cacheManager.Add("CategoryMenu", menustr, CacheItemPriority.High, null, new AbsoluteTime(DateTime.Now.AddMinutes(5)));
                    cacheManager.Add("CategoryMenu_Long", menustr, CacheItemPriority.High, null, new AbsoluteTime(DateTime.Now.AddDays(1)));
                }
                catch
                {
                    cacheManager.Add("CategoryMenu", cacheManager.GetData("CategoryMenu_Long").ToString(), CacheItemPriority.High, null, new AbsoluteTime(DateTime.Now.AddMinutes(5)));
                    menustr = cacheManager.GetData("CategoryMenu").ToString();
                }
            }

            /*Ek Menü*/
            string addtmenustr = "";
            if (Parameters.AdditionMenuCategoryId > 0)
            {
                addtmenustr = (string)cacheManager.GetData("AddtCategoryMenu");
                if (addtmenustr == null)
                {
                    try
                    {
                        addtmenustr = dbCategory.GetMenu(Parameters.AdditionMenuCategoryId);
                        cacheManager.Add("AddtCategoryMenu", addtmenustr, CacheItemPriority.High, null, new AbsoluteTime(DateTime.Now.AddMinutes(5)));
                        cacheManager.Add("AddtCategoryMenu_Long", addtmenustr, CacheItemPriority.High, null, new AbsoluteTime(DateTime.Now.AddDays(1)));
                    }
                    catch
                    {
                        cacheManager.Add("AddtCategoryMenu", cacheManager.GetData("AddtCategoryMenu_Long").ToString(), CacheItemPriority.High, null, new AbsoluteTime(DateTime.Now.AddMinutes(5)));
                        addtmenustr = cacheManager.GetData("AddtCategoryMenu").ToString();
                    }
                }

            }
            /*Ek Menü*/

            MenuModel model = new MenuModel();
            model.Menu = menustr;
            model.MenuType = MenuType;
            model.AdditionMenu = addtmenustr;
            return PartialView(model);
        }

        #endregion

        #region Categories2

        public ActionResult Categories2(int full = 0, string id = "SelectedCategory", string GroupType = "A")
        {
            ViewBag.ShowAll = full == 1 ? true : false;
            ViewBag.Id = id;
            var CacheName = id + "Combo";
            var seciniz = "";
            switch (GroupType)
            {
                case "A": seciniz = "Kategori Seçiniz"; break;
                case "S": seciniz = "Grup Seçiniz"; break;
                case "D": seciniz = "Kategori Seçiniz"; break;
                case "M": seciniz = "Marka Seçiniz"; break;
                default: seciniz = "Kategori Seçiniz"; break;
            }

            var cacheManager = CacheFactory.GetCacheManager("Cache Manager");

            IList<ProductGroup> categories = (List<ProductGroup>)cacheManager.GetData(CacheName);
            if (categories == null)
            {
                try
                {
                    categories = dbProduct.GetGroupListFull(GroupType);
                    categories.Insert(0, new ProductGroup { GroupId = 0, GroupName = seciniz });

                    cacheManager.Add(CacheName, categories, CacheItemPriority.High, null, new AbsoluteTime(DateTime.Now.AddMinutes(5)));
                    cacheManager.Add(CacheName + "_Long", categories, CacheItemPriority.High, null, new AbsoluteTime(DateTime.Now.AddDays(1)));
                }
                catch
                {
                    cacheManager.Add(CacheName, cacheManager.GetData(CacheName + "_Long").ToString(), CacheItemPriority.High, null, new AbsoluteTime(DateTime.Now.AddMinutes(5)));
                    categories = (List<ProductGroup>)cacheManager.GetData(CacheName);
                }
            }

            CategoryModel2 model = new CategoryModel2();
            model.Categories = categories;
            return PartialView(model);
        }

        #endregion

        #region BestSeller

        public ActionResult BestSeller()
        {
            var cacheKey = "PartialBestSeller";
            if (HttpRuntime.Cache[cacheKey] != null)
            {
                return PartialView(HttpRuntime.Cache[cacheKey] as ProductsModel);
            }

            int PageStart = 0;
            int PageEnd = 150;
            int? id = Parameters.BestSellingCategoryId;

            var productsModel = new ProductsModel();
            if (id.HasValue)
            {
                productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, 0, eStoreUser.AccountId, "").Skip(PageStart).Take(PageEnd).OrderBy(o => o.SiraNo == 0).ThenBy(o => o.SiraNo).ToArray<Product>();
            }
            productsModel.IsManager = eStoreUser.IsManager;
            productsModel.BasketLocked = eStoreUser.BasketLocked;

            HttpRuntime.Cache.Add(cacheKey, productsModel, null, DateTime.UtcNow.AddDays(1), Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.NotRemovable, null);

            return PartialView(productsModel);
        }

        #endregion

        #region OurSuggestions

        public ActionResult OurSuggestions()
        {
            var cacheKey = "PartialOurSuggestions";
            if (HttpRuntime.Cache[cacheKey] != null)
            {
                return PartialView(HttpRuntime.Cache[cacheKey] as ProductsModel);
            }


            int PageStart = 0;
            int PageEnd = 150;
            int? id = Parameters.OurSuggestionsCategoryId;

            ProductsModel productsModel = new ProductsModel();
            if (id.HasValue)
            {
                productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, 0, eStoreUser.AccountId, "").Skip(PageStart).Take(PageEnd).OrderBy(o => o.SiraNo == 0).ThenBy(o => o.SiraNo).ToArray<Product>();
            }
            CategoryMeta cm = dbCategory.GetMeta((int)id);
            Category category = dbCategory.Get((int)id);
            if (category != null)
            {
                Mapper.MapDomainToViewModel(category, productsModel);
                productsModel.CategoryType = category.CategoryType;
                productsModel.RelatedItemShowCount = category.RelatedItemShowCount;
                productsModel.ListImageType = cm.ListImageType;
                if (productsModel.RelatedItemShowCount > 0)
                {
                    productsModel.RelatedProducts = productsModel.RelatedProducts.Take(productsModel.RelatedItemShowCount).ToArray<Product>();
                }
            }
            else
            {
                productsModel.CategoryType = "S";
                productsModel.RelatedItemShowCount = 0;
                productsModel.RelatedProducts = null;
                productsModel.RelatedItemCount = 0;
            }
            var posListe = dbPos.GetList().FirstOrDefault(o => o.PosVoucher == "S");
            if (posListe != null)
            {
                posListe.PosInstallment = dbPos.GetInstallmentList(posListe.PosId, 1, 9999, 0, 0);
                productsModel.VoucherRate = posListe.PosInstallment != null ? posListe.PosInstallment.FirstOrDefault(o => o.InstallmentNumber == 10).CommissionRate : (1 + (Parameters.SenetEkUcret / 100));
            }
            productsModel.CategoryId = (int)id;

            productsModel.IsManager = eStoreUser.IsManager;
            productsModel.BasketLocked = eStoreUser.BasketLocked;
            HttpRuntime.Cache.Add(cacheKey, productsModel, null, DateTime.UtcNow.AddDays(1), Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.NotRemovable, null);

            return PartialView(productsModel);
        }

        #endregion

        #region DailyOffers

        public ActionResult DailyOffers()
        {
            var cacheKey = "DailyOffers";
            if (HttpRuntime.Cache[cacheKey] != null)
            {
                return PartialView(HttpRuntime.Cache[cacheKey] as KL.Store.Web.Models.ProductsModel);
            }

            int PageStart = 0;
            int PageEnd = 150;
            int? id = Parameters.DailyOffersCategoryId;

            var productsModel = new ProductsModel();
            if (id.HasValue)
            {
                productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, 0, eStoreUser.AccountId, "").Skip(PageStart).Take(PageEnd).OrderBy(o => o.SiraNo == 0).ThenBy(o => o.SiraNo).ToArray<Product>();
            }
            CategoryMeta cm = dbCategory.GetMeta((int)id);
            Category category = dbCategory.Get((int)id);
            if (category != null)
            {
                Mapper.MapDomainToViewModel(category, productsModel);
                productsModel.CategoryType = category.CategoryType;
                productsModel.RelatedItemShowCount = category.RelatedItemShowCount;
                productsModel.ListImageType = cm.ListImageType;
                if (productsModel.RelatedItemShowCount > 0)
                {
                    productsModel.RelatedProducts = productsModel.RelatedProducts.Take(productsModel.RelatedItemShowCount).ToArray<Product>();
                }
            }
            else
            {
                productsModel.CategoryType = "S";
                productsModel.RelatedItemShowCount = 0;
                productsModel.RelatedProducts = null;
                productsModel.RelatedItemCount = 0;
            }
            var posListe = dbPos.GetList().FirstOrDefault(o => o.PosVoucher == "S");
            if (posListe != null)
            {
                posListe.PosInstallment = dbPos.GetInstallmentList(posListe.PosId, 1, 9999, 0, 0);
                productsModel.VoucherRate = posListe.PosInstallment != null ? posListe.PosInstallment.FirstOrDefault(o => o.InstallmentNumber == 10).CommissionRate : (1 + (Parameters.SenetEkUcret / 100));
            }
            productsModel.CategoryId = (int)id;

            productsModel.IsManager = eStoreUser.IsManager;
            productsModel.BasketLocked = eStoreUser.BasketLocked;
            HttpRuntime.Cache.Add(cacheKey, productsModel, null, DateTime.UtcNow.AddDays(1), Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.NotRemovable, null);
            return PartialView(productsModel);
        }

        #endregion

        #region BestSeller2

        public ActionResult BestSeller2(int totalItemCount)
        {
            var cacheKey = "BestSeller2";
            if (HttpRuntime.Cache[cacheKey] != null)
            {
                return PartialView(HttpRuntime.Cache[cacheKey] as ProductsModel);
            }

            var productsModel = new ProductsModel
            {
                RelatedProducts =
                    dbProduct.GetBestSellerList(0, 0, 0, eStoreUser.AccountId, "", totalItemCount, "SATIS")
                        .OrderByDescending(o => o.BillOut)
                        .ThenByDescending(o => o.CreatedDate)
                        .ToArray<Product>()
            };

            CategoryMeta cm = dbCategory.GetMeta(Parameters.MainCategoryId);
            Category category = dbCategory.Get(Parameters.MainCategoryId);
            if (category != null)
            {
                Mapper.MapDomainToViewModel(category, productsModel);
                productsModel.CategoryType = category.CategoryType;
                productsModel.RelatedItemShowCount = category.RelatedItemShowCount;
                productsModel.ListImageType = cm.ListImageType;
                if (productsModel.RelatedItemShowCount > 0)
                {
                    productsModel.RelatedProducts = productsModel.RelatedProducts.Take(productsModel.RelatedItemShowCount).ToArray<Product>();
                }
            }
            else
            {
                productsModel.CategoryType = "S";
                productsModel.RelatedItemShowCount = 0;
                productsModel.RelatedProducts = null;
                productsModel.RelatedItemCount = 0;
            }
            var posListe = dbPos.GetList().FirstOrDefault(o => o.PosVoucher == "S");
            if (posListe != null)
            {
                posListe.PosInstallment = dbPos.GetInstallmentList(posListe.PosId, 1, 9999, 0, 0);
                productsModel.VoucherRate = posListe.PosInstallment != null ? posListe.PosInstallment.FirstOrDefault(o => o.InstallmentNumber == 10).CommissionRate : (1 + (Parameters.SenetEkUcret / 100));
            }
            productsModel.CategoryId = Parameters.MainCategoryId;

            productsModel.IsManager = eStoreUser.IsManager;
            productsModel.BasketLocked = eStoreUser.BasketLocked;

            HttpRuntime.Cache.Add(cacheKey, productsModel, null, DateTime.UtcNow.AddDays(1), Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.NotRemovable, null);

            return PartialView(productsModel);
        }

        #endregion

        #region RelatedProductsInCategory

        public ActionResult RelatedProductsInCategory(int CategoryId, string CategoryName, int ItemId, int itemCount, string Position, string Title = "", bool randomOrder = false)
        {
            ViewBag.CurrentItemId = ItemId;
            ViewBag.RelatedPosition = Position;
            ViewBag.PartialTitle = Title;

            var cacheKey = "RelatedProductsInCategory" + CategoryId + CategoryName + ItemId + itemCount + Position + Title + randomOrder;
            if (HttpRuntime.Cache[cacheKey] != null)
            {
                return PartialView(HttpRuntime.Cache[cacheKey] as KL.Store.Web.Models.ProductsModel);
            }

            int PageStart = 0;
            int PageEnd = itemCount;
            int? id = CategoryId;
       
            var productsModel = new ProductsModel();
            if (id.HasValue)
            {
                productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, 0, eStoreUser.AccountId, "").Where(o => o.ProductId != ItemId && o.UstUrunId != ItemId).ToArray<Product>();
                if (randomOrder)
                {
                    var rand = new Random();
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderBy(o => rand.Next()).Skip(PageStart).Take(PageEnd).ToArray<Product>();
                }
                else
                {
                    productsModel.RelatedProducts = productsModel.RelatedProducts.Skip(PageStart).Take(PageEnd).OrderBy(o => o.CreatedDate).OrderByDescending(o => o.TotalViewCount).ToArray<Product>();
                }
            }
            var posListe = dbPos.GetList().FirstOrDefault(o => o.PosVoucher == "S");
            if (posListe != null)
            {
                posListe.PosInstallment = dbPos.GetInstallmentList(posListe.PosId, 1, 9999, 0, 0);
                productsModel.VoucherRate = posListe.PosInstallment != null ? posListe.PosInstallment.FirstOrDefault(o => o.InstallmentNumber == 10).CommissionRate : (1 + (Parameters.SenetEkUcret / 100));
            }
            productsModel.CategoryId = CategoryId;
            productsModel.CategoryName = CategoryName;
            productsModel.BasketLocked = eStoreUser.BasketLocked;
            HttpRuntime.Cache.Add(cacheKey, productsModel, null, DateTime.UtcNow.AddDays(1), Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.NotRemovable, null);
            return PartialView(productsModel);
        }

        #endregion

        #region RelatedLists

        public ActionResult RelatedLists()
        {
            var cacheKey = "RelatedLists";
            if (HttpRuntime.Cache[cacheKey] != null)
            {
                return View(HttpRuntime.Cache[cacheKey] as KL.Store.Web.Models.RelatedUsersModel);
            }

            if (eStoreUser.AccountId > 0)
            {
                var RelatedUsers = new RelatedUsersModel();
                RelatedUsers.Users = dbWishLists.GetRelatedUsers(eStoreUser.AccountId);

                if (RelatedUsers.Users.Count > 0)
                {
                    HttpRuntime.Cache.Add(cacheKey, RelatedUsers, null, DateTime.UtcNow.AddDays(1), Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.NotRemovable, null);
                    return View(RelatedUsers);
                }
            }
            return null;
        }

        #endregion

        #region Account

        public ActionResult Account()
        {
            return View();
        }

        #endregion

        #region Information

        public ActionResult Information()
        {
            return View();
        }

        #endregion

        #region Login

        public ActionResult Login()
        {
            ActiveAccountModel aaModel = new ActiveAccountModel();
            aaModel.StoreUserName = (eStoreUser.FirstName + ' ' + eStoreUser.LastName).TrimEnd();
            aaModel.StoreUserId = eStoreUser.AccountId > 0 && eStoreUser.AccountId != null ? eStoreUser.AccountId : 0;
            return View(aaModel);
        }

        #endregion

        #region MailListForm

        public ActionResult MailListForm(string placeHolder, string submitText)
        {
            MailListModel mailListModel = new MailListModel();
            mailListModel.placeholder = placeHolder;
            mailListModel.submittext = submitText;
            return PartialView(mailListModel);
        }

        #endregion

        #region SaveMailList

        [Child]
        public ActionResult SaveMailList(string eposta)
        {
            string insertResult = dbContactUs.InsertMailList(eposta);
            //return Content(cus.Id.ToString() + " numaralı mesajınız iletilmiştir.");
            return Content("<script>alert('" + insertResult + "');</script>");

        }

        #endregion

        #region FacebookLikeBox

        public ActionResult FacebookLikeBox()
        {
            return View();
        }

        #endregion

        #region ManageContentLink

        public ActionResult ManageContentLink(int id)
        {
            ViewBag.IsManager = eStoreUser.IsManager;
            ViewBag.ContentId = id;
            return View();
        }

        #endregion

        #region SearchBrandAndProducts

        public ActionResult SearchBrandAndProducts()
        {
            if (eStoreUser.IsManager || eStoreUser.IsSeoManager)
            {
                ViewBag.Manager = true;
            }
            else
            {
                ViewBag.Manager = false;
            }
            return View();
        }

        #endregion

    }
}
